﻿using System;
using System.Collections.Generic;
using AutoMapper;

namespace Adapter
{
    public class DefaultProfile<E, D> : Profile
    {

        /// <summary>
        /// E2D自定义转化集合
        /// </summary>
        public Dictionary<System.Linq.Expressions.Expression<Func<D, object>>, System.Linq.Expressions.Expression<Func<E, object>>> E2DDict { get; set; }

        /// <summary>
        /// D2E自定义转化集合
        /// </summary>
        public Dictionary<System.Linq.Expressions.Expression<Func<E, object>>, System.Linq.Expressions.Expression<Func<D, object>>> D2EDict { get; set; }

        /// <summary>
        /// 构造函数
        /// </summary>
        public DefaultProfile()
        {
            E2DDict = new Dictionary<System.Linq.Expressions.Expression<Func<D, object>>, System.Linq.Expressions.Expression<Func<E, object>>>();
            D2EDict = new Dictionary<System.Linq.Expressions.Expression<Func<E, object>>, System.Linq.Expressions.Expression<Func<D, object>>>();
        }

        protected void AddE2DMember(System.Linq.Expressions.Expression<Func<D, object>> dtoExpression, System.Linq.Expressions.Expression<Func<E, object>> entityExpression)
        {
            E2DDict.Add(dtoExpression, entityExpression);
        }

        protected void AddD2EMember(System.Linq.Expressions.Expression<Func<E, object>> entityExpression, System.Linq.Expressions.Expression<Func<D, object>> dtoExpression)
        {
            D2EDict.Add(entityExpression, dtoExpression);
        }
        /// <summary>
        /// 配置
        /// </summary>
        protected override void Configure()
        {

            var e2d = CreateMap<E, D>();
            var d2e = CreateMap<D, E>();
            foreach (var item in E2DDict)
            {
                Action<IMemberConfigurationExpression<E, D, object>> memberOptions = new Action<IMemberConfigurationExpression<E, D, object>>(opt => opt.MapFrom(item.Value));
                e2d = e2d.ForMember(item.Key, memberOptions);
            }

            foreach (var item in D2EDict)
            {
                Action<IMemberConfigurationExpression<D, E, object>> memberOptions = new Action<IMemberConfigurationExpression<D, E, object>>(opt => opt.MapFrom(item.Value));
                d2e = d2e.ForMember(item.Key, memberOptions);
            }
        }

    }
}
